<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" :border="true" :stripe="true">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              class="vcenter"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  :closable="true"
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级 -->
              <el-col :span="19">
                <el-row
                  class="vcenter"
                  :class="[i2 !== 0 ? 'bdtop' : '']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      :closable="true"
                      @close="removeRightsById(scope.row, item2.id)"
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--三级  -->
                  <el-col :span="18">
                    <el-row
                      class="vcenter"
                      :class="[i3 !== 0 ? 'bdtop' : '']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                    >
                      <el-col>
                        <el-tag
                          type="warning"
                          :closable="true"
                          @close="removeRightsById(scope.row, item3.id)"
                          >{{ item3.authName }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showsetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
    <!-- 树型控件 -->
    <el-tree :data="rightsList" :props="setRightTreeProps"
    show-checkbox
    default-expand-all
    node-key="id"
    :default-checked-keys="defaultRightsId"
    ref="treeRef"
    >
    </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      rolesList: [],
      // 是否展示对话框
      setRightDialogVisible: false,
      // 所有权限列表
      rightsList: [],
      // Tree控件展示的Props
      setRightTreeProps:{
        children: 'children',
          label: 'authName'
      },
      // 角色已经有的权限id
      defaultRightsId:[],
      // 即将分配权限的角色ID
      roleId:''

    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data;
      // console.log(this.rolesList);
    },
    // 根据角色id和权限id 删除对应权限
    async removeRightsById(role, rightId) {
    
      // 先弹出一个提示框是否继续删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除！");
      }
      // 确认删除
      const { data: res } = await this.$axios.delete(
        `roles/${role.id}/rights/${rightId}`
      );

      if (res.meta.status !== 200) {
        this.$message.error("删除权限失败！");
      }

      role.children = res.data;
    },
    // 显示分配权限对话框
    async showsetRightDialog(role) {
        // 保存分配角色的id
        this.roleId=role.id
      // 1、先展示对话框
      this.setRightDialogVisible = true;
      // 2、获取所有权限
      const { data: res } = await this.$axios.get("rights/tree");
      this.rightsList = res.data;
      this.getLeafKeys(role,this.defaultRightsId)
    },
    // 获取角色已经有的权限id
    getLeafKeys(node,arr){
      // 如果当前node 节点不包含children 属性，则是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      // 如果node有孩子节点就递归直到找到没有孩子的节点
      node.children.forEach(item=>this.getLeafKeys(item,arr))
    },
    setRightDialogClosed(){
      this.defaultRightsId=[]
    },
    // 点击为角色分配权限
    async allotRights(){
      const keys=[
        ...this.$refs.treeRef.getCheckedNodes(),
        ...this.$refs.treeRef.getHalfCheckedNodes(),
      ]
     const keyStr=keys.join(',')
    const{data:res}= await  this.$axios.post(`roles/${this.roleId}/rights`,{rids :keyStr})
    if(res.meta.status!==200){
      return this.$message.error('添加权限失败')
    }
    this.$message.success('添加权限成功！')
    // 这里添加的角色权限但是getRolesList方法中请求回来的roleList 还是原来的数据，并没有改变，所以没有渲染出来角色新的权限

    this.getRolesList()
    this.setRightDialogVisible=false

    }

  },
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
